import { defineComponent, reactive, ref } from 'vue';
import './index.less';
import type { DeckDetail } from '/@/api/verse/model/deckModel';
import { ReviewStatusEnum } from '/@/api/verse/model/deckModel';
import { aTabClick, awaitWrap, getTokenUrl } from '/@/utils';
import { DeckDetailApi, ExportDeckImgApi } from '/@/api/verse/deck';
import Title from '/@/views/verse/components/Title';
import { Skeleton } from 'vant';
import DeckSelectCardList from '/@/views/verse/components/DeckSelectCardList/DeckSelectCardList';
import { Icon } from '/@/components/Icon';
import { appShareUsing, appShareParamsEncrypt } from '/@/utils/appInteractive';
// import { downloadByOnlineUrl } from '/@/utils/file/download';
import { useMessage } from '/@/hooks/web/useMessage';
import { useGo } from '/@/hooks/web/usePage';

export default defineComponent({
  name: 'VerseDeckDetailPage',
  props: {
    id: {
      type: String as PropType<string>,
      required: true,
    },
    share: {
      type: String as PropType<string>,
      default: () => {
        return '';
      },
    },
  },
  setup(props) {
    const content = {
      title: '旅法师营地-影之诗Evolve套牌',
      content: '我通过旅法师营地跟你分享影之诗Evolve套牌，点击查看',
      image: 'https://pic.iyingdi.com/yingdi_mobile/yingdi-logo.png',
      url: window.location.href + '?share=1',
    };
    // 设置分享参数
    appShareUsing(content);

    const go = useGo();

    const { createLoadingToast, clearToast, createInfoToast } = useMessage();

    const cardDetailInfo = reactive<DeckDetail>({} as DeckDetail);
    const loadingState = ref(true);
    const getDetail = async () => {
      const [error, data] = await awaitWrap(DeckDetailApi({ id: Number(props.id) }));
      if (error) {
        return false;
      }
      const result = data as DeckDetail;
      for (const item in result) {
        cardDetailInfo[item] = result[item];
      }
      loadingState.value = false;
    };
    getDetail();

    // 主战者
    const FighterArea = () => {
      const { main_fighters } = cardDetailInfo;
      return (
        <div class={'fighter-area'}>
          <div class={'name-box text-sm flex'}>
            <h5 class={'leading-none'}>主战者：</h5>
            <div class={'name-content leading-none'}>
              {main_fighters.map((item, index) => {
                const name = main_fighters.length === index + 1 ? item.name : `${item.name}、`;
                return (
                  <span>
                    {item.card_career}-{name}
                  </span>
                );
              })}
            </div>
          </div>
          <ul class={'image-box flex flex-wrap'}>
            {main_fighters.map((item) => {
              return (
                <li class={'image'}>
                  <img src={item.thumbnail} alt='' />
                </li>
              );
            })}
          </ul>
        </div>
      );
    };
    // 卡牌标题
    const DeckNameArea = () => {
      let spanAbbr: VueNode = null;
      switch (cardDetailInfo.review_status) {
        case ReviewStatusEnum.ING:
          spanAbbr = <span class={'text-red-500'}>（审核中）</span>;
          break;
        case ReviewStatusEnum.FAIL:
          spanAbbr = <span class={'text-red-500'}>（未通过）</span>;
          break;
      }
      return (
        <div class={'deck-name-area flex justify-between'}>
          <span class={'flex-1'}>{cardDetailInfo.deck_name}</span>
          {spanAbbr}
        </div>
      );
    };

    // 分享事件
    const shareClick = () => {
      content.title = cardDetailInfo.deck_name;
      const base64str = appShareParamsEncrypt(JSON.stringify(content));
      aTabClick(`wanxiu://innerlink?type=webshareurl&parameters=${base64str}`);
    };
    const downLoadImageClick = async () => {
      createLoadingToast({
        message: '生成图片中',
        overlay: true,
      });
      const [error, data] = await awaitWrap(ExportDeckImgApi({ id: cardDetailInfo.id }));
      if (error) {
        clearToast();
        return;
      }
      clearToast();
      if (!data) {
        createInfoToast({ message: '图片正在生成中..', overlay: true });
        return;
      }
      aTabClick(data!, '_blank');
      /*const imageName = new Date().valueOf() + Math.ceil(Math.random() * 10000) + '.png';
      downloadByOnlineUrl(data!, imageName);*/
    };

    return () => (
      <div class={'deck-detail-page'}>
        <Title
          title={cardDetailInfo.deck_name}
          leftArrow={!props.share}
          onLeftClick={() => {
            go(getTokenUrl('/versedeck'), true);
          }}
        />
        <Skeleton title row={5} avatar loading={loadingState.value}>
          <div class={'detail-container'}>
            <DeckNameArea />
            <FighterArea />
            <DeckSelectCardList mainCards={cardDetailInfo.main_cards} otherCards={cardDetailInfo.other_cards} />
          </div>
        </Skeleton>

        {!props.share ? (
          <ul class={'action-area flex items-center justify-between'}>
            <li class={'exprot flex flex-col items-center'} onClick={downLoadImageClick}>
              <Icon class={'!text-xl mb-sm'} icon={'bi:image'} />
              <span>导出</span>
            </li>
            <li
              class={'modify flex flex-col items-center'}
              onClick={() => {
                go(`/versecreate/${props.id}`, true);
              }}
            >
              <Icon class={'!text-xl mb-sm'} icon={'material-symbols:edit-calendar-outline'} />
              <span>编辑</span>
            </li>
            <li class={'share flex flex-col items-center'} onClick={shareClick}>
              <Icon class={'!text-xl mb-sm'} icon={'ri:share-circle-line'} />
              <span>分享</span>
            </li>
          </ul>
        ) : null}
      </div>
    );
  },
});
